﻿using System;
using Castle.DynamicProxy;
using Wisdom.Core;

namespace Wisdom.Core
{
    /// <summary>
    /// 描述：异常处理拦截器
    /// </summary>
    public class ExceptionHandlingInterceptor : IInterceptor
    {
        #region Private Methods
        private object GetReturnValueByType(Type type)
        {
            if (type.IsClass || type.IsInterface)
                return null;
            if (type == typeof(void))
                return null;
            return Activator.CreateInstance(type);
        }
        #endregion

        #region IInterceptor Members
        /// <summary>
        /// 执行拦截行为 
        /// </summary>
        /// <param name="invocation">拦截代理.</param>
        public void Intercept(IInvocation invocation)
        {
            try
            {
                invocation.Proceed();
            }
            catch (Exception ex)
            {
                invocation.ReturnValue = GetReturnValueByType(invocation.Method.ReturnType);
                bool handled = ExceptionManager.HandleException(ex);
                if (!handled)
                    throw;
            }
        }

        #endregion
    }
}
